﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////


#include "GbmpNew.h"
#include "IJournalRecordEventReceiver.h"
#include "IJournalUiEvent.h"
#include "IJournalUiObject.h"
#include "JournalConfig.h"
#include "JournalPropertyPalletRecorder.h"
#include "JournalUtils.h"
#include "QKeyTextMap.h"
#include "StringUtil.h"
#include <QWidget>
#include <qevent.h>
#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"

using namespace gcmp;

namespace gfam
{
    class ViewMouseMoveEventFilter : public IJournalRecordEventReceiver
    {
    public:
        virtual bool ShouldIgnoreRecordQEvent(const gcmp::IJournalUiObject *pIUIObject, const gcmp::IJournalUiEvent *pIUIEvent) const override { return false; }

        virtual bool ShouldIgnoreRecordQWidget(const gcmp::IJournalUiObject *pIUIObject) const override { return false; }

        virtual bool ShouldIgnoreVerifyQWidget(const gcmp::IJournalUiObject *pIUIObject) const override { return false; }

        virtual bool ShouldFilterEvent(const IJournalUiObject *pIUiObject, const IJournalUiEvent *pIUiEvent) const override;
    };

    bool ViewMouseMoveEventFilter::ShouldFilterEvent(const IJournalUiObject *pIUiObject, const IJournalUiEvent *pIUiEvent) const
    {
        DBG_WARN_AND_RETURN_UNLESS(pIUiObject && pIUiEvent, false, L"输入pIUIObject和pIUIEvent不应该有为空的情况", L"paramodel", L"2024-02-20");

        QObject *pObject = pIUiObject->GetUiObject().cast<QObject*>();
        DBG_WARN_AND_RETURN_UNLESS(pObject, false, L"输入pIUIObject中存储的控件对象类型不是QObject", L"paramodel", L"2024-02-20");
        QEvent *pEvent = pIUiEvent->GetUiEvent().cast<QEvent*>();
        DBG_WARN_AND_RETURN_UNLESS(pEvent, false, L"输入pIUIEvent中存储的事件对象类型不是QEvent", L"paramodel", L"2024-02-20");

        DBG_WARN_AND_RETURN_FALSE_UNLESS(pObject->metaObject(), L"pObject->metaObject()为空", L"paramodel", L"2024-02-20");
        QString className = pObject->metaObject()->className();
        if (className == QString("gcmp::impl::QtUIView") && pEvent->type() == QEvent::MouseMove)
        {
            return true;
        }

        return false;
    }
}

gfam::JournalPropertyPalletRecorder::JournalPropertyPalletRecorder(QObject *pParent)
    : m_pParent(pParent)
{
}

gfam::JournalPropertyPalletRecorder::~JournalPropertyPalletRecorder(void)
{
}

bool gfam::JournalPropertyPalletRecorder::RecordMouseLeaveEvent( QObject *pObject,const QString &buttonType,int x,int y, std::map<std::wstring, std::wstring> &journalParameter, bool &filterEvent )
{    
    static bool isRecordingMouseLeaveEvent = false;
    if(IsMouseLeaveEvent(pObject))
    {
        if (isRecordingMouseLeaveEvent)
        {
            filterEvent = true;
            return false;
        }
        isRecordingMouseLeaveEvent = true;

        // 录制时，清除焦点之后会产生一个leaveEvent和mouseMoveEvent
        // 需要将mouseMove过滤掉
        // 因为清除焦点只是想要结束编辑控件的编辑状态，不应该有mouseMove
        QWidget *pWidget = dynamic_cast<QWidget*>(pObject);
        DBG_WARN_AND_RETURN_FALSE_UNLESS(pWidget, L"属性面板不是QWidget？", L"paramodel", L"2024-02-20");
        OwnerPtr<IJournalRecordEventReceiver> opFilter = NEW_AS_OWNER_PTR(ViewMouseMoveEventFilter);
        JournalUtils::RegisterJournalRecordEventReceiver(opFilter.get());
        // 清除子控件的focus使有机会记录EditText
        if (QWidget *pWidget = dynamic_cast<QWidget*>(pObject))
        {
            QWidget *pFocusWidget = pWidget->focusWidget();
            if (pFocusWidget)
            {
                pFocusWidget->clearFocus();
            }
        }
        JournalUtils::UnregisterJournalRecordEventReceiver(opFilter.get());

        journalParameter[JRN_PARAM_BUTTON_TYPE] = buttonType.toStdWString();
        journalParameter[JRN_PARAM_MOUSE_POSE_X] = StringUtil::ToWString(x);
        journalParameter[JRN_PARAM_MOUSE_POSE_Y] = StringUtil::ToWString(y);

        isRecordingMouseLeaveEvent = false;
        return true;
    }
    return false;
}

//PropertyPalette内子控件(例如，QComboBox)的激活，会导致光标脱离自身
bool gfam::JournalPropertyPalletRecorder::IsMouseLeaveEvent( QObject *pObject )
{
    QWidget* pWidget = dynamic_cast<QWidget*>(pObject);
    DBG_WARN_AND_RETURN_FALSE_UNLESS(pWidget != nullptr, L"接收leaveEvent的QObject不是QWidget", L"paramodel", L"2024-02-20");
    
    // widget coordinate
    QRect rect(0, 0, pWidget->width(), pWidget->height());
    // the global screen coordinate pos to widget coordinates.
    QPoint cursorPoint = pWidget->mapFromGlobal(QCursor::pos());
    if(rect.contains(cursorPoint))
    {
        return false;
    }
    else
    {
        return true;
    }
}

bool gfam::JournalPropertyPalletRecorder::Record(IJournalUiObject *pIUiObject, IJournalUiEvent *pIUiEvent, std::wstring &eventType, std::map<std::wstring, std::wstring> &journalParameter, bool &filterEvent)
{
    DBG_WARN_AND_RETURN_UNLESS(pIUiObject && pIUiEvent, false, L"输入pIUIObject和pIUIEvent不应该有为空的情况", L"paramodel", L"2024-02-20");

    QObject *pQtObject = pIUiObject->GetUiObject().cast<QObject*>();
    DBG_WARN_AND_RETURN_UNLESS(pQtObject, false, L"输入pObject中存储的控件对象类型不是QObject", L"paramodel", L"2024-02-20");
    QEvent *pQtEvent = pIUiEvent->GetUiEvent().cast<QEvent*>();
    DBG_WARN_AND_RETURN_UNLESS(pQtEvent, false, L"输入pEvent中存储的事件对象类型不是QEvent", L"paramodel", L"2024-02-20");

    QString buttonType = "Left";
    QPoint eventPos;

    if (QMouseEvent *pMouseEvent = dynamic_cast<QMouseEvent*>(pQtEvent))
    {
        if (pMouseEvent->button() == Qt::MiddleButton)
        {
            buttonType = "Middle";
        }
        else if (pMouseEvent->button() == Qt::RightButton)
        {
            buttonType = "Right";
        }
        else if (pMouseEvent->button() == Qt::NoButton)
        {
            buttonType = "No";
        }
        eventPos = pMouseEvent->pos();
    }

    if (QEvent::Leave == pQtEvent->type())
    {
        eventType = JRN_EVENT_TYPE_MOUSE_LEAVE;
        return RecordMouseLeaveEvent(pQtObject, buttonType, eventPos.x(), eventPos.y(), journalParameter, filterEvent);
    }
    else if (QEvent::KeyPress == pQtEvent->type() || QEvent::KeyRelease == pQtEvent->type())
    {
        QKeyEvent *pKeyEvent = dynamic_cast<QKeyEvent*>(pQtEvent);
        DBG_WARN_AND_RETURN_FALSE_UNLESS(pKeyEvent, L"pKeyEvent为空", L"paramodel", L"2024-02-20");
        int key = pKeyEvent->key();
        int modifier = pKeyEvent->modifiers();

        journalParameter[JRN_PARAM_KEY_VALUE] = QKeyTextMap::Singleton().GetQKeyText(key);
        journalParameter[JRN_PARAM_KEY_MODIFIER] = QKeyTextMap::Singleton().GetQKeyboardModifierText(modifier);

        if (QEvent::KeyPress == pQtEvent->type())
        {
            eventType = JRN_EVENT_TYPE_KEY_PRESS;
            Qt::Key keyType = (Qt::Key)key;
            if (keyType == Qt::Key_Return || keyType == Qt::Key_Enter || keyType == Qt::Key_Escape)
            {
                // 清除子控件的focus使有机会记录EditText
                if (QWidget *pWidget = dynamic_cast<QWidget*>(pQtObject))
                {
                    QWidget *pFocusWidget = pWidget->focusWidget();
                    if (pFocusWidget)
                    {
                        pFocusWidget->clearFocus();
                    }
                }
            }
        }
        else
        {
            eventType = JRN_EVENT_TYPE_KEY_REALEASE;
        }
        return true;
    }

    return false;
}
